package com.wooboo.server.ext.data;

import java.util.Date;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Map.Entry;

import com.aspire.portal.web.security.client.GenerateSignature;
import com.aspire.portal.web.security.client.VerifySignature;
import com.wooboo.server.ext.ApiError;
import com.wooboo.server.ext.Config;
import com.wooboo.server.ext.constants.Status;
import com.wooboo.server.ext.constants.Status.Flow;
import com.wooboo.server.ext.service.DbService;
import com.wooboo.server.ext.util.DateUtil;
import com.wooboo.server.ext.util.HttpClientUtils;
import com.wooboo.server.ext.util.NumberUtil;
import com.wooboo.server.ext.util.StringUtil;
import com.wooboo.server.ext.util.http.HttpUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Traffic {

	public static String KEY_PATH="config/private.key";
	public static String PUBLIC_PATH="config/public.key";
	
	
	public static String key="/Users/luoyouhua/Documents/work/private.key";
	public static String TRAFFIC_CALL_URI=Config.getValue("traffic.call.uri");
	public static String PORTAL_ID=Config.getValue("portal.id");
	public static String PORTAL_TYPE=Config.getValue("portal.type");
	public static String IP_LIST=Config.getValue("traffic.ip.list");
	public static enum Method{companyRegisterApply,companyNodeRegisterApply,companyContractRegisterApply,companyFlowPkgRechargeApply,companyFlowPkgHandsel,queryCompanyFlowPkgAcct};
	public static enum Action{insert,update,delete};
	public static Integer API_STATUS_NONE=0;//未接入
	public static Integer API_STATUS_REGISTER=1; //已申请
	public static Integer API_STATUS_APPLY=2; //已经接入
	
	/**
	 * 企业信息注册申请（营销平台—>流量+）
	 * @throws ApiError 
	 * */
	public static JSONObject companyRegisterApply(UserCompany com) throws ApiError{
		String dateStr = DateUtil.getFormatDate(new Date(), "yyyyMMddHHmmss");
		SortedMap<String, String> params =  new TreeMap<String, String>();
		params.put("portalType", Traffic.PORTAL_TYPE);//门户类型 
		params.put("portalID", Traffic.PORTAL_ID);
		params.put("transactionID",dateStr+StringUtil.createId(8));//交易唯一编码：yyyMMddHHmmss+8位唯一序号
		params.put("method", Traffic.Method.companyRegisterApply.toString());//方法
		params.put("company_name", StringUtil.dealNull(com.getCompany_name()));//公司
		params.put("province_name", StringUtil.dealNull(com.getProvince_name()));//省份
		params.put("city_name", StringUtil.dealNull(com.getCity_name()));//城市
		params.put("company_addr", StringUtil.dealNull(com.getCompany_addr()));//地址
        params.put("post_code", StringUtil.dealNull(com.getPost_code()));//邮政编码
 		params.put("company_nature", StringUtil.dealNull(com.getCompany_nature()));//企业性质 0 私营 1 国有 2 联营 3 外资 4 其它
		params.put("company_industry", StringUtil.dealNull(com.getCompany_industry()));//所属行业 0 农业 1 工业 2 服务业 3 交通运输 4 其它
		params.put("company_type", StringUtil.dealNull(com.getCompany_type()));//企业类型 0 工商认证企业 1 普通商户 2 地市移动公司 3 政府部门
		params.put("registration_type", StringUtil.dealNull(com.getRegistration_type()));//企业证件号类型: BL 营业执照注册号 UC 统一社会信用代码
		params.put("registration_no", StringUtil.dealNull(com.getRegistration_no()));//营业执照注册号或统一社会信用代码
		params.put("foundation_date", StringUtil.dealNull(com.getFoundation_date()));//成立日期，YYYY-MM-DD
		params.put("business_term", StringUtil.dealNull(com.getBusiness_term()));//营业期限
		params.put("foundation_date", StringUtil.dealNull(com.getFoundation_date()));//营业期限
		params.put("registered_capital", StringUtil.dealNull(com.getRegistered_capital()));//注册资本
		params.put("legal_person", StringUtil.dealNull(com.getLegal_person()));//法人
		params.put("legal_person_id_no", StringUtil.dealNull(com.getLegal_person_id_no()));//法人证件
		params.put("legal_person_mobile", StringUtil.dealNull(com.getLegal_person_mobile()));//法人手机号
		params.put("contacts", StringUtil.dealNull(com.getContacts()));//联系人姓名
		params.put("contact_mobile", StringUtil.dealNull(com.getContact_mobile()));//联系人手机
		params.put("contact_email", StringUtil.dealNull(com.getContact_email()));//联系人邮箱
		params.put("create_time", DateUtil.getFormatDate(com.getCreate_time(), "yyyyMMddHHmmss"));//注册时间
		params.put("sign", Traffic.sign(params));
		//params.put("contact_email", StringUtil.encode(params.get("contact_email"), "utf-8"));//联系人邮箱
		
		System.out.println(params.get("contact_email"));
		JSONObject response=HttpClientUtils.postFromUrl4Json(Traffic.TRAFFIC_CALL_URI, params);
		return response;
	}
	/**
	 * 企业接入信息注册申请（营销平台—>流量平台）
	 * @throws ApiError 
	 * */
	public static JSONObject companyNodeRegisterApply(UserCompany com,String actionType) throws ApiError{
		SortedMap<String, String> params =  new TreeMap<String, String>();
		params.put("portalType", Traffic.PORTAL_TYPE);//门户类型 
		params.put("portalID", Traffic.PORTAL_ID);
		params.put("company_code",StringUtil.dealNull(com.company_code));
		params.put("method", Method.companyNodeRegisterApply.toString());//方法
		JSONObject data = new JSONObject();
		JSONArray node_action_list = new JSONArray();
		JSONObject json = new JSONObject();
		json.put("action_type", actionType);
		//json.put("portal_id", PORTAL_ID);
		json.put("portal_id", StringUtil.dealNull(com.company_code));
		json.put("portal_type", PORTAL_TYPE);
		json.put("ip_list", IP_LIST);
		node_action_list.add(json);
		data.put("node_action_list", node_action_list);
		params.put("node_action_list", data.toString());
		params.put("sign", Traffic.sign(params));
		JSONObject response= HttpClientUtils.postFromUrl4Json(Traffic.TRAFFIC_CALL_URI, params);
		return response;
	}
	/**
	 * 企业合同注册申请 
	 * @throws ApiError 
	 * */
	public static JSONObject companyContractRegisterApply(UserCompany com,ChargeOrder order,List<TrafficGift> list) throws ApiError{
		SortedMap<String, String> params =  new TreeMap<String, String>();
		params.put("portalType", Traffic.PORTAL_TYPE);//门户类型 
		params.put("portalID", Traffic.PORTAL_ID);
		params.put("method", Method.companyContractRegisterApply.toString());//方法
		params.put("company_code",StringUtil.dealNull(com.company_code));
		params.put("contract_number", order.order_no);//合同编号
		params.put("start_date", DateUtil.getFormatDate(order.start_date, "yyyyMMdd"));
		params.put("end_date", DateUtil.getFormatDate(order.end_date, "yyyyMMdd"));
		params.put("contract_amount", StringUtil.dealNull(order.amount));
		params.put("contract_desc", order.order_no+StringUtil.dealNull(order.msg));

		JSONObject data = new JSONObject();
		JSONArray product_list = new JSONArray();
		for(TrafficGift tg:list){
			JSONObject json = new JSONObject();
			json.put("product_id", tg.getCode());
			json.put("product_name", tg.getName());
			json.put("product_value", NumberUtil.formatYuan(tg.getPrice(), "#0.0000"));
			product_list.add(json);
		}
		data.put("product_list", product_list);
		params.put("product_list", data.toString());
		params.put("sign", Traffic.sign(params));
		JSONObject response= HttpClientUtils.postFromUrl4Json(Traffic.TRAFFIC_CALL_URI, params);
		return response;
	}
	/**
	 * 充值
	 * @throws ApiError 
	 * */
	public static JSONObject companyFlowPkgRechargeApply(UserCompany com,ChargeOrder order) throws ApiError{
		String datetime = DateUtil.getFormatDate(new Date(), "yyyymmddHHmmss");
		String sequence = PORTAL_TYPE+PORTAL_ID+datetime+StringUtil.createId(6);
		
		SortedMap<String, String> params =  new TreeMap<String, String>();
		params.put("portalType", Traffic.PORTAL_TYPE);//门户类型 
		params.put("portalID", Traffic.PORTAL_ID);
		params.put("method", Method.companyFlowPkgRechargeApply.toString());//方法
		params.put("sequence", sequence);//业务流水号
		params.put("company_code",StringUtil.dealNull(com.company_code));//公司编号
		params.put("account_no", order.getContact_account_no());
		
		
		params.put("recharge_amount",StringUtil.dealNull(order.amount));//充值金额
		params.put("oper_time", datetime);//交易时间
		params.put("sign", Traffic.sign(params));
	
		JSONObject response= HttpClientUtils.postFromUrl4Json(Traffic.TRAFFIC_CALL_URI, params);
		return response;
	}
	/**
	 * 流量赠送
	 * @throws ApiError 
	 * */
	public static JSONObject companyFlowPkgHandsel(UserCompany com ,TrafficGift flow,Ad ad,PhoneTrafficGift g) throws ApiError{
		String datetime = DateUtil.getFormatDate(new Date(), "yyyymmddHHmmss");
		String sequence = PORTAL_TYPE+PORTAL_ID+datetime+StringUtil.createId(6);
		//
		g.setSequence(sequence);
		 
		SortedMap<String, String> params =  new TreeMap<String, String>();
		params.put("portalType", Traffic.PORTAL_TYPE);//门户类型 
		params.put("portalID", Traffic.PORTAL_ID);
		params.put("transactionID",datetime+StringUtil.createId(8));//交易唯一编码：yyyMMddHHmmss+8位唯一序号
		params.put("method", Method.companyFlowPkgHandsel.toString());//方法
		params.put("sequence", sequence);//业务流水号
        params.put("company_code", com.getCompany_code());
        params.put("org_acct_no", ad.getContact_account_no());
        params.put("oper_time", datetime);
        params.put("notify_url", Config.getValue("traffic.gift.notifyurl"));
        JSONObject oper_data_list = new JSONObject();
        JSONArray array = new JSONArray();
        JSONObject p = new JSONObject();
        p.put("msisdn", g.phone_number);
        p.put("product_id", flow.getCode());
        p.put("product_value", StringUtil.dealNull(flow.getPrice()));
        array.add(p);
        oper_data_list.put("user_list", array);
        params.put("oper_data_list", oper_data_list.toString());
        params.put("sign", Traffic.sign(params));
        
        
        JSONObject response= HttpClientUtils.postFromUrl4Json(Traffic.TRAFFIC_CALL_URI, params);
		return response;
	}
	
	public static void queryCompanyFlowPkgAcct(UserCompany com) throws ApiError{
		String datetime = DateUtil.getFormatDate(new Date(), "yyyymmddHHmmss");		
		SortedMap<String, String> params =  new TreeMap<String, String>();
		params.put("portalType", Traffic.PORTAL_TYPE);//门户类型 
		params.put("portalID", Traffic.PORTAL_ID);
		params.put("transactionID",datetime+StringUtil.createId(8));//交易唯一编码：yyyMMddHHmmss+8位唯一序号
		params.put("method", Method.queryCompanyFlowPkgAcct.toString());//方法
		params.put("company_code", com.getCompany_code());
		params.put("sign", Traffic.sign(params));
		
		JSONObject response= HttpClientUtils.postFromUrl4Json(Traffic.TRAFFIC_CALL_URI, params);
		System.out.println(response.toString());
	}
	
	public static String sign(SortedMap<String, String> params){
		String info = toSignString(params);
		String path = Thread.currentThread().getContextClassLoader().getResource(KEY_PATH).getPath();
		System.out.println(info+"   "+path);
		return sign(info, path);
	}
	public static String publicSign(SortedMap<String, String> params){
		String info = toSignString(params);
		String path = Thread.currentThread().getContextClassLoader().getResource(PUBLIC_PATH).getPath();
		System.out.println(info+"   "+path);
		return sign(info, path);
	}
	
	private static String sign(String info,String path){
		GenerateSignature gs = new GenerateSignature();
		return gs.sign(info, path);
	}
	public static boolean verify(SortedMap<String, String> params,String sign){
		String info = toSignString(params);
		VerifySignature vs = new VerifySignature();
		String path = Thread.currentThread().getContextClassLoader().getResource(PUBLIC_PATH).getPath();
        return vs.verify(info, sign, path);
	}
	
	
	
	private static String toSignString(SortedMap<String, String> map){
		StringBuffer sbuf = new StringBuffer();
		boolean b = true;
		for(Entry<String, String> en:map.entrySet()){
			if(!StringUtil.isEmpty(en.getValue())){
				sbuf.append((b?"":"&")+en.getKey()+"="+en.getValue());
				if(b){b=false;}
			}
		}
		return sbuf.toString();//MD5Util.MD5Encode(sbuf.toString(), charset).toUpperCase();
	}
	
	
	
	public static void main(String[] args){
		//String str = "company_code=8000000955&method=companyFlowPkgHandselNofity&msisdn=13700000060&oper_time=20170505134918&portalID=105010805&portalType=WAP&product_id=10001&result=999&sequence=WAP10501080520175105135104884976&sign=5414296b66216ca525d9813af77ba1e5eb2ee163cb92f834fa0db00175b6edede4c45a8f42222d5eaee760547426da58311d5ab457016a11a6abedc881e004c671def758538af2a452b203162e10f727dab4bfd3fc390bab990b8a92b15438fe47f0be283747a1fb9204503810449746a256bcef11e73eb536a6a2253199d60e&transactionID=2017510513510485340224";
		
		String str = "company_code=8000000955&method=companyFlowPkgHandselNofity&msisdn=13700000060&oper_time=20170505134918&portalID=105010805&portalType=WAP&product_id=10001&result=999&sequence=WAP10501080520175105135104884976&transactionID=2017510513510485340224&sign=5414296b66216ca525d9813af77ba1e5eb2ee163cb92f834fa0db00175b6edede4c45a8f42222d5eaee760547426da58311d5ab457016a11a6abedc881e004c671def758538af2a452b203162e10f727dab4bfd3fc390bab990b8a92b15438fe47f0be283747a1fb9204503810449746a256bcef11e73eb536a6a2253199d60e";

		String path = Thread.currentThread().getContextClassLoader().getResource(KEY_PATH).getPath();
		//System.out.println(info+"   "+path);
		String strs =  sign(str, path);
		System.out.println(strs);
		
		
		
		
//		UserCompany com;
//		try {
//			com = new DbService().findCompanyById(7);
//			Traffic.queryCompanyFlowPkgAcct(com);
//		} catch (ApiError e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
				
	}
	
	
	
}
